from urllib import request, parse
from lxml import etree
import ssl

# 取消 https 代理验证
ssl._create_default_https_context = ssl._create_unverified_context


def aiqiyi(self, name):
    # 报头
    user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36'
    headers = {'User-Agent': user_agent}
    url = "https://so.iqiyi.com/so/q_" + parse.quote(name)
    req = request.Request(url, headers=headers)
    try:
        response = request.urlopen(req)
        # 获取每页的HTML源码字符串
        html = response.read().decode('utf-8')
        # 解析html 为 HTML 文档
        selector = etree.HTML(html)

        # 来源
        source = "爱奇艺视频"

        # 剧照
        pic = 'https:' + selector.xpath('//div[@class="layout-main"]/div[2]//img[@class="qy-mod-cover"]/@src')[0]

        # 链接
        link = selector.xpath('//div[@class="layout-main"]/div[2]//a[@class="qy-mod-link"]/@href')[0]

        # 导演
        director_list = selector.xpath('//div[@class="layout-main"]/div[2]//div[@class="qy-search-result-info half"][1]/a')
        director_node_list = []
        for node in director_list:
            director = node.xpath('@title')[0]
            director_node_list.append(director)

        # 主演
        actor_list = selector.xpath('//div[@class="layout-main"]/div[2]//div[@class="qy-search-result-info half"][2]/a')
        actor_node_list = []
        for node in actor_list:
            actor = node.xpath('@title')[0]
            actor_node_list.append(actor)

        # # 地区
        # area = \
        #     selector.xpath(
        #         '//div[@class="layout-main"]/div[2]//div[@class="qy-search-result-info half"][3]/span/text()')[0]
        #
        # # 上映时间
        # update_time = \
        #     selector.xpath(
        #         '//div[@class="layout-main"]/div[2]//div[@class="qy-search-result-info half"][4]/span/text()')[0]

        # 简介
        desc = \
            selector.xpath(
                '//div[@class="layout-main"]/div[2]//div[@class="qy-search-result-info multiple"]/span/text()')[
                0]

        defalut_result = {
            "source": source,
            "name": name,
            # "area": area,
            # "update_time": update_time,
            "pic": pic,
            "director": director_node_list,
            "actor": actor_node_list,
            "desc": desc,
            "list": [{'title': '播放', 'link': link}]
        }
        return defalut_result
    except Exception:
        print(url, Exception)
        data = {"code": -1, "message": "error", "data": None}
        return data
